import store from "@/store"
import { setToken } from "@/store/actions/user"
import { message } from "antd"
import axios from "axios"
import history from "@/utils/history"
import { clearToken } from "./auth"

const instance = axios.create({
    timeout: 5000,
    baseURL: "http://toutiao.itheima.net",
})

instance.interceptors.request.use(config => {
    const { user: { token } } = store.getState()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => Promise.reject(error))

instance.interceptors.response.use(
    (response) => {
        return response ? response?.data : response
    },
    (error) => {
        if (error.response.status === 401) {
            message.error('登陆失效')
            clearToken()
            store.dispatch(setToken(""))
            history.push({
                pathname: '/login',
                state: { from: history.location.pathname }
            })
        }
        Promise.reject(error)
    }
)

export default instance
